package com.example.myapplication.xiaochengxu;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: rongfeng
 * @date: 2020/12/10
 * @description
 */
public class DowdLoadImg {
    List<caier.Bean.TrackList> urlList = new ArrayList<>();
    volatile int mIndex = -1;
    ExecutorService pool;

    public void addList(List<caier.Bean.TrackList> list) {
        urlList = list;
         start();
    }


    public void start() {
        pool = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 3; i++) {
            next();
        }
    }

    public void next() {
        pool.execute(new Runnable() {
            @Override
            public void run() {
                mIndex++;
                if (mIndex < urlList.size()) {
                    download(urlList.get(mIndex));
                }
            }
        });
    }

    public void download(caier.Bean.TrackList data) {
        // 下载网络文件
        int bytesum = 0;
        int byteread = 0;

        URL url = null;
//        try {
////            url = new URL(data.icon);
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        }
        InputStream inStream = null;
        FileOutputStream fs = null;
        try {
            URLConnection conn = url.openConnection();
            inStream = conn.getInputStream();
            fs = new FileOutputStream("D:\\wrf\\test\\img\\" + data.trackId + ".png");
            byte[] buffer = new byte[1024];
            int length;
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fs != null) {
                try {
                    fs.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        next();
        System.out.println("ssss " + mIndex);
    }


}
